﻿using System.Windows.Input;
using CardPlay.Client.ViewModels;

namespace CardPlay.Client.Tools
{
    public class InvokeActionTool : Tool
    {
        public InvokeActionTool(IToolSite site) : base(site)
        {
            State = Inactive;
        }

        protected override void OnDeactivated()
        {
            CaptureElement = null;
            State = Inactive;
        }

        private IPlayingContext PlayingContext
        {
            get { return (IPlayingContext) Site.GetService(typeof (IPlayingContext));  }
        }

        private void Inactive(InputEvent inputEvent)
        {
            if (inputEvent.Name != InputEvent.MouseLeftButtonDown) return;

            var args = (MouseButtonEventArgs) inputEvent.Args;
            var position = args.GetPosition(inputEvent.InputElement);

            var location = PlayingContext.Canvas.HitTest((int) position.X, (int) position.Y);
            if (location.IsUndefined) return;
            
#if SILVERLIGHT
            if (!PlayingContext.InvokeActionAt(location)) return;

            CaptureElement = inputEvent.InputElement;
            IsActivated = true;
            State = Tracking;
#else
            switch (args.ClickCount)
            {
                case 1:
                    if (! PlayingContext.InvokeActionAt(location)) return;

                    CaptureElement = inputEvent.InputElement;
                    IsActivated = true;
                    State = Tracking;
                    break;

                case 2:
                    PlayingContext.InvokeAutoActionAt(location);
                    break;
            }
#endif
        }

        private void Tracking(InputEvent inputEvent)
        {
            if (inputEvent.Name != InputEvent.MouseLeftButtonUp) return;
            IsActivated = false;
        }
    }
}